﻿#region 文件信息

/*----------------------------------------------------------------
//
// 文件名称：
// 文件功能描述：
// 设计要求：
//
// 文 件 名：    RoleService
// 创建者：      杨程
// 创建日期：	    2023/1/19 14:45:42

//----------------------------------------------------------------*/

#endregion

namespace Vampirewal.Admin.Server.RpcServices.Service;

/// <summary>
/// 角色RPC服务
/// </summary>
public partial class RoleService : RpcServiceBasic
{
    /// <summary>
    ///
    /// </summary>
    public RoleService()
    {
        //构造函数
    }

    #region [     新增     ]

    /// <summary>
    /// 新增角色模版
    /// </summary>
    /// <param name="callContext"></param>
    /// <param name="role"></param>
    [LogWrite]
    [Description("新增角色模版")]
    [ActionFilter]
    [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
    public void CreateRole(ICallContext callContext, Sys_RoleTemplate role)
    {
        callContext.CheckCaller(out Sys_User user);
        if (!user.IsAdmin)
        {
            throw new Exception("非管理员不允许操作！");
        }
        var repRoleTemplate = SqlSugarRepository<Sys_RoleTemplate>();
        try
        {
            repRoleTemplate.CurrentBeginTran();

            repRoleTemplate.Insert(role);

            repRoleTemplate.CurrentCommitTran();
        }
        catch (Exception ex)
        {
            repRoleTemplate.CurrentRollbackTran();
            throw ex;
        }
    }

    /// <summary>
    /// 操作用户角色关联信息(新增或更新)
    /// </summary>
    /// <param name="callContext"></param>
    /// <param name="userRole"></param>
    [LogWrite]
    [Description("操作用户角色关联信息(新增或更新)")]
    [ActionFilter]
    [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
    public void OperationUserRole(ICallContext callContext, Sys_UserRole userRole)
    {
        callContext.CheckCaller(out Sys_User user);
        if (!user.IsAdmin)
        {
            throw new Exception("非管理员不允许操作！");
        }

        var repUserRole = SqlSugarRepository<Sys_UserRole>();

        var Cur = repUserRole.Single(s => s.UserId == userRole.UserId);
        try
        {
            repUserRole.CurrentBeginTran();

            if (Cur != null)
            {
                Cur.RoleId = userRole.RoleId;
                repUserRole.Update(Cur);
            }
            else
            {
                repUserRole.Insert(userRole);
            }

            repUserRole.CurrentCommitTran();
        }
        catch (Exception ex)
        {
            repUserRole.CurrentRollbackTran();
            throw ex;
        }
    }

    #endregion

    #region [     修改     ]

    /// <summary>
    /// 修改角色模版
    /// </summary>
    /// <param name="callContext"></param>
    /// <param name="role"></param>
    [LogWrite]
    [Description("修改角色模版")]
    [ActionFilter]
    [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
    public void UpdateRole(ICallContext callContext, Sys_RoleTemplate role)
    {
        callContext.CheckCaller(out Sys_User user);
        if (!user.IsAdmin)
        {
            throw new Exception("非管理员不允许操作！");
        }
        var repRoleTemplate = SqlSugarRepository<Sys_RoleTemplate>();
        try
        {
            repRoleTemplate.CurrentBeginTran();

            repRoleTemplate.Update(role);

            repRoleTemplate.CurrentCommitTran();
        }
        catch (Exception ex)
        {
            repRoleTemplate.CurrentRollbackTran();
            throw ex;
        }
    }

    #endregion

    #region [     删除     ]

    /// <summary>
    /// 删除角色模版
    /// </summary>
    /// <param name="callContext"></param>
    /// <param name="role"></param>
    [LogWrite]
    [Description("删除角色模版")]
    [ActionFilter]
    [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
    public void DeleteRole(ICallContext callContext, Sys_RoleTemplate role)
    {
        callContext.CheckCaller(out Sys_User user);
        if (!user.IsAdmin)
        {
            throw new Exception("非管理员不允许操作！");
        }

        var repRoleTemplate = SqlSugarRepository<Sys_RoleTemplate>();
        var repUserRole = SqlSugarRepository<Sys_UserRole>();

        if (repUserRole.Any(a => a.RoleId == role.BillId))
        {
            throw new Exception("还存在绑定角色的用户，无法删除！");
        }
        else
        {
            try
            {
                repRoleTemplate.CurrentBeginTran();

                repRoleTemplate.Delete(role);

                repRoleTemplate.CurrentCommitTran();
            }
            catch (Exception ex)
            {
                repRoleTemplate.CurrentRollbackTran();
                throw ex;
            }
        }
    }

    /// <summary>
    /// 删除用户角色关联信息
    /// </summary>
    /// <param name="callContext"></param>
    /// <param name="userrole"></param>
    [LogWrite]
    [Description("删除用户角色关联信息")]
    [ActionFilter]
    [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
    public void DeleteUserRole(ICallContext callContext, Sys_UserRole userrole)
    {
        callContext.CheckCaller(out Sys_User user);
        if (!user.IsAdmin)
        {
            throw new Exception("非管理员不允许操作！");
        }
        var repUserRole = SqlSugarRepository<Sys_UserRole>();
        try
        {
            repUserRole.CurrentBeginTran();

            repUserRole.Delete(userrole);

            repUserRole.CurrentCommitTran();
        }
        catch (Exception ex)
        {
            repUserRole.CurrentRollbackTran();
            throw ex;
        }
    }

    #endregion

    #region [     查询     ]

    /// <summary>
    /// 查询当前租户下的所有角色模版(租户管理员才能使用)
    /// </summary>
    /// <param name="callContext"></param>
    /// <returns></returns>
    [Description("查询当前租户下的所有角色模版(租户管理员才能使用)")]
    [ActionFilter]
    [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
    public List<Sys_RoleTemplate> QueryRoleTemplate(ICallContext callContext)
    {
        callContext.CheckCaller(out Sys_User user);
        if (!user.IsAdmin)
        {
            throw new Exception("非管理员不允许操作！");
        }

        return SqlSugarRepository<Sys_RoleTemplate>().ToList(s => s.TenantId == user.TenantId && s.RoleName != "超级管理员");
    }

    /// <summary>
    /// 分页获取角色模版(租户管理员才能使用)
    /// </summary>
    /// <param name="callContext"></param>
    /// <param name="request"></param>
    /// <returns></returns>
    [Description("分页获取角色模版(租户管理员才能使用)")]
    [ActionFilter]
    [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
    public PageContainer<Sys_RoleTemplate> GetPageRoleTemplateList(ICallContext callContext, RolePageRequest request)
    {
        var repUser = SqlSugarRepository<Sys_RoleTemplate>();
        int total = 0;
        int totalPage = 0;

        var OrgIds = GetRoleDataScope(callContext);

        callContext.CheckCaller(out Sys_User user);
        var dbresult = repUser.AsQueryable().Where(f => f.TenantId == user.TenantId)
                                                          .WhereIF(!string.IsNullOrEmpty(request.OrgId), f => f.OrgId == request.OrgId)
                                                          .Where(f => OrgIds.Contains(f.OrgId))
                                                          .ToPageList(request.Page, request.Limit, ref total, ref totalPage);

        PageContainer<Sys_RoleTemplate> container = new PageContainer<Sys_RoleTemplate>();
        container.Data = dbresult;
        container.TotalCount = total;
        container.PageCount = totalPage;
        container.Count = dbresult.Count;

        return container;
    }

    /// <summary>
    /// 根据机构ID获取当前机构下的角色模版(租户管理员才能使用)
    /// </summary>
    /// <param name="callContext"></param>
    /// <param name="OrgId">机构ID</param>
    /// <returns></returns>
    [Description("根据机构ID获取当前机构下的角色模版(租户管理员才能使用)")]
    [ActionFilter]
    [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
    public List<Sys_RoleTemplate> GetRoleTemplatesByOrgId(ICallContext callContext, string OrgId)
    {
        callContext.CheckCaller(out Sys_User user);
        if (!user.IsAdmin)
        {
            throw new Exception("非管理员不允许操作！");
        }

        return SqlSugarRepository<Sys_RoleTemplate>().ToList(s => s.TenantId == user.TenantId && s.OrgId == OrgId && s.RoleName != "超级管理员");
    }



    /// <summary>
    /// 获取当前用户的数据权限
    /// </summary>
    /// <param name="callContext"></param>
    /// <returns></returns>
    [Description("获取当前用户的数据权限")]
    [ActionFilter]
    [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
    public List<string> GetRoleDataScope(ICallContext callContext)
    {
        callContext.CheckCaller(out Sys_User user);

        var repRoleTemplate = SqlSugarRepository<Sys_RoleTemplate>();

        if (user.IsAdmin)
        {
            return repRoleTemplate.Change<Sys_Org>().ToList(t => t.TenantId == user.TenantId && t.State).Select(s => s.BillId).ToList();
        }
        //先获取到用户角色关联表
        var userRole = repRoleTemplate.Change<Sys_UserRole>().Single(s => s.UserId == user.BillId);
        //获取当前用户的角色模版
        var roleTemp = repRoleTemplate.Single(s => s.TenantId == user.TenantId && s.BillId == userRole.RoleId);

        List<string> OrgList = new List<string>();

        switch (roleTemp.DataScope)
        {
            case 0:
                OrgList = repRoleTemplate.Change<Sys_Org>().ToList(t => t.TenantId == user.TenantId && t.State).Select(s => s.BillId).ToList();
                break;

            case 1:
                FindChildOrg(repRoleTemplate.Change<Sys_Org>(), user.OrgId, ref OrgList);
                if (!OrgList.Any(a => a.Equals(user.OrgId)))
                {
                    OrgList.Add(user.OrgId);
                }
                break;

            case 2:
                OrgList.Add(user.OrgId);
                break;

            case 3:
                //没有其他数据权限，就只能查看自己的
                break;
        }

        return OrgList;
    }

    #endregion

    private void FindChildOrg(SqlSugarRepository<Sys_Org> Repository, string ParentOrgId, ref List<string> OrgIds)
    {
        var Childs = Repository.ToList(t => t.ParentId == ParentOrgId);

        foreach (var org in Childs)
        {
            FindChildOrg(Repository, org.BillId, ref OrgIds);

            OrgIds.Add(org.BillId);
        }
    }
}